<!--  -->
<template>
    <page-header-wrapper @back="() => $router.go(-1)">
        <a-card :bordered="false" >
            <a-button slot="extra" type="primary" @click="add">新增收件地址</a-button>
            <a-table style="margin-top: 20px" rowKey="id" :loading="isload" :columns="columns" :data-source="dataList" @change="handleTableChange" :pagination="{ total: total ,showSizeChanger: true,pageSize: size,}" size="small">
                <div slot="operation" slot-scope="text,record">
                    <div class="editable-row-operations">
                        <a-button type="link" v-if="record.isDefault == 1">默认地址</a-button>
                        <a-popconfirm
                            v-else
                            title="是否设置当前收件地址为默认地址?"
                            ok-text="Yes"
                            cancel-text="No"
                            @confirm="setDefault(record,1)"
                        >
                            <a-button type="link">设为默认</a-button>
                        </a-popconfirm>
                        <a-button type="link" @click="update(record)">修改</a-button>
                        <a-popconfirm
                            title="是否删除当前收件地址?"
                            ok-text="Yes"
                            cancel-text="No"
                            @confirm="del(record,1)"
                        >
                            <a-button type="link">删除</a-button>
                        </a-popconfirm>
                    </div>
                </div>
            </a-table>
        </a-card>

        <!-- 添加、修改收件地址 -->
        <a-modal 
            v-model="visible" 
            width="60%"
            :title="isAdd ? '添加地址' : '编辑地址'"
            @ok="handleOk" 
            :forceRender="true"
            @cancel="visible = false">
            <div>
                <a-form-model :model="address" ref="ruleForm" :rules="rules" :label-col="{ span: 7 }" :wrapper-col="{ span: 17 }">
                    <a-form-model-item label="收件人姓名" prop="userName">
                        <a-input v-model="address.userName" placeholder="请输入收件人姓名" />
                    </a-form-model-item>
                    <a-form-model-item label="邮寄地址" prop="area">
                        <a-row :gutter='48'>
                            <a-col :md='8' :sm='24'>
                                <a-select v-model="address.province" placeholder="省份" @change="selProvince">
                                    <a-select-option v-for="item in provinceList" :key="item.value" :value="item.label">{{item.label}}</a-select-option>
                                </a-select>
                            </a-col>
                            <a-col :md='8' :sm='24'>
                                <a-select v-model="address.city" placeholder="城市" @change="selCity">
                                    <a-select-option v-for="item in cityList" :key="item.value" :value="item.label">{{item.label}}</a-select-option>
                                </a-select>
                            </a-col>
                            <a-col :md='8' :sm='24'>
                                <a-select v-model="address.area" placeholder="区域">
                                    <a-select-option v-for="item in areaList" :key="item.value" :value="item.label">{{item.label}}</a-select-option>
                                </a-select>
                            </a-col>
                        </a-row>
                        
                    </a-form-model-item>
                    <a-form-model-item label="详细地址" prop="address">
                        <a-input v-model="address.address" placeholder="填写街道地址，不必重复省市信息" />
                    </a-form-model-item>
                    <a-form-model-item label="联系方式" prop="phone">
                        <a-input v-model="address.phone" placeholder="请输入联系方式" />
                    </a-form-model-item>
                </a-form-model>
            </div>
        </a-modal>
    </page-header-wrapper>
</template>

<script>
import { columns } from './table';
import { getReceiptAddress , createReceiptAddress , updateReceiptAddress , setReceiptAddressDefault , deleteReceiptAddress } from '@/api/companys/invoice';
import area from '@/assets/area';
export default {
    data () {
        return {
            dataList: [],
            isload: false,
            page: 1,
            size: 10,
            total: 0,
            columns,
            address: {
                id: '',
                userName: '', // 收件人姓名
                province: undefined, // 省份
                city: undefined, // 城市
                area: undefined, // 区域
                address: '', // 详细地址
                phone: '', // 联系方式
            },
            isAdd: true,
            visible: false,
            rules: {
                userName: [
                    { required: true, message: '请输入收件人姓名', trigger: 'blur' },
                ],
                area: [{ required: true, message: '请选择省市区', trigger: 'blur' }],
                address: [{ required: true, message: '请输入详细地址', trigger: 'blur' }],
                phone: [
                    { required: true, message: '请输入联系方式', trigger: 'blur' },
                ],
            },
            provinceList: [],
            cityList: [],
            areaList: [],
        };
    },
    created(){
        var list = [];
        for (const key in area.province_list) {
            if (area.province_list.hasOwnProperty(key)) {
                list.push({
                    'label': area.province_list[key],
                    'value': `${key}`,
                })
            }
        }
        this.provinceList = list;
        this.getData();
    },
    methods: {
        // 获取发票地址列表
        getData(){
            let _this = this;
            _this.isload = true;
            const params = {
                'pageSize': _this.size,
                'pageIndex': _this.page,
            }
            getReceiptAddress(params)
            .then(res => {
                _this.isload = false;
                if(res.success){
                    _this.dataList = res.data;
                    _this.total = res.totalCount
                }else{
                    _this.$notification['error']({
                        message: '温馨提示',
                        description: res.errMessage,
                        duration: 8
                    })
                }
            })
        },
        // 分页
        handleTableChange(pagination, filters, sorter) {
            console.log(pagination);
            this.page = pagination.current;
            this.size = pagination.pageSize;
            this.getData()
        },
        // 添加地址
        add(){
            this.$refs.ruleForm.resetFields();
            this.address.id = ''
            this.isAdd = true;
            this.visible = true;
        },
        update(item){
            this.address = JSON.parse(JSON.stringify(item));
            this.selProvince(this.address.province,1)
            this.selCity(this.address.city,1)
            this.isAdd = false;
            this.visible = true;
        },
        // 确认添加、修改地址
        handleOk(){
            let _this = this;
            _this.$refs.ruleForm.validate(valid => {
                if(valid){
                    var api = _this.isAdd ? createReceiptAddress(_this.address) : updateReceiptAddress(_this.address)
                    api.then(res=>{
                        if(res.success){
                            _this.$notification['success']({
                                message: '温馨提示',
                                description: _this.isAdd ? '添加成功' : '修改成功',
                                duration: 8
                            })
                            _this.visible = false;
                            _this.getData()
                        }else{
                            _this.$notification['error']({
                                message: '温馨提示',
                                description: res.errMessage,
                                duration: 8
                            })
                        }
                    })
                }
            })
        },
        // 省市区选择
        selProvince(val,type){
            console.log(val,'province')
            var provinceCode = this.provinceList.find(item => item.label == val).value.substring(0,2)
            let list = [];
            for (const key in area.city_list) {
                if (area.city_list.hasOwnProperty(key)) {
                    if(key.substring(0,2) == provinceCode){
                        list.push({
                            'label': area.city_list[key],
                            'value': key,
                        })
                    }
                }
            }
            this.cityList = list;
            if(type != 1)this.address.city = undefined;
        },
        selCity(val,type){
            console.log(val,'city')
            var cityCode = this.cityList.find(item => item.label == val).value.substring(0,4)
            let list = [];
            for (const key in area.county_list) {
                if (area.county_list.hasOwnProperty(key)) {
                    if(key.substring(0,4) == cityCode){
                        list.push({
                            'label': area.county_list[key],
                            'value': key,
                        })
                    }
                }
            }
            this.areaList = list;
            if(type != 1)this.address.area = undefined;
        },
        // 设为默认地址
        setDefault(item){
            let _this = this;
            setReceiptAddressDefault(item.id)
            .then(res => {
                if(res.success){
                    _this.$notification['success']({
                        message: '温馨提示',
                        description: '设置成功',
                        duration: 8
                    })
                    _this.getData();
                }else{
                    _this.$notification['error']({
                        message: '温馨提示',
                        description: res.errMessage,
                        duration: 8
                    })
                }
            })
        },
        // 删除发票收货地址
        del(item){
            let _this = this;
            // if(item.isDefault == 1){
            //     _this.$message.warning('默认收件地址无法删除');
            //     return;
            // }
            deleteReceiptAddress(item.id)
            .then(res => {
                if(res.success){
                    _this.$notification['success']({
                        message: '温馨提示',
                        description: '删除成功',
                        duration: 8
                    })
                    _this.getData();
                }else{
                    _this.$notification['error']({
                        message: '温馨提示',
                        description: res.errMessage,
                        duration: 8
                    })
                }
            })
        },
    }
}

</script>
<style scoped>

</style>